﻿;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Logistics.BoxupPack", [])
        .controller("BoxupPackCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "EventBus", "Upload", "ybConfig", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, EventBus, Upload, ybConfig, UserContextService) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.datePickerFlag = [false, false, false, false, false, false];
            $scope.subTabFlag = [true, false];

            // 权限模块
            var btnPermissionCode = {
                boxupNoAdd: window.ActionCode.boxupNoAdd,
                boxupNoUpdate: window.ActionCode.boxupNoUpdate,
                boxupNoDelete: window.ActionCode.boxupNoDelete,
                boxupNoAudit: window.ActionCode.boxupNoAudit,
                boxupNoDelivery: window.ActionCode.boxupNoDelivery,
                boxupNoPrint: window.ActionCode.boxupNoPrint,
                boxupNoExport: window.ActionCode.boxupNoExport,
            };

            $scope.btnPermission = {
                boxupNoAdd: true,
                boxupNoUpdate: true,
                boxupNoDelete: true,
                boxupNoAudit: true,
                boxupNoDelivery: true,
                boxupNoPrint: true,
                boxupNoExport: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }
            
            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    },
                    scrollLeftWidth: {
                        width: $scope.tableConfig.fixedWidth + "px"
                    },
                    billFixedWidth: {
                        left: $scope.addLeftTableConfig.fixedWidth + "px"
                    }
                };
            };

            $scope.markInfo = {
                allChecked: false
            };
            $scope.boxupPackStatus = {
                '-1':'草稿',
                '0' : '未审核',
                '1' : '通过',
                '2' : '拒绝'
            }
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.detailPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.orderMarkInfo = {
                allChecked: false
            };
            $scope.orderPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 50,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.condition = {};
            $scope.orderCondition = {
                status: '1'
            };
            $scope.dataList = [];
            $scope.orderDataList = [];
            $scope.selectedList = [];
            $scope.detailInfo = {};
            
            $scope.showDatepicker = false;
            $scope.showDatepicker1 = false;
            $scope.packageMethodList = [];
            $scope.packageSpecListAll = [];
            $scope.packageInfo = {
                barcodeList: [],
            };

            // 主页面列表
            $scope.tableConfig = {
                scrollWidth: 1700,
                fixedWidth: 300,
                tableCol: [
                    {
                        type: "",
                        name: "打包单号",
                        dataField: "packNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail"
                    },
                    {
                        type: "",
                        name: "单据状态",
                        dataField: "statusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "发运状态",
                        dataField: "deliveryStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "国家和地区",
                        dataField: "country",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "接收人",
                        dataField: "acceptName",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "审核时间",
                        dataField: "checkTimeShow",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "审核意见",
                        dataField: "checkMessage",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createTimeShow",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "发运人",
                        dataField: "deliveryName",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "发运时间",
                        dataField: "deliveryTimeShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "要求发运日期",
                        dataField: "requireDeliveryTimeShow",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "发运地址",
                        dataField: "deliveryAddress",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        isShow: true,
                        isFixed: true,
                        width: 260,
                    },
                ]
            };

            //新增时左侧列表配置项
            $scope.addLeftTableConfig = {
                scrollWidth: 600,
                fixedWidth: 40,
                tableCol: [
                    {
                        type: "",
                        name: "箱单号",
                        dataField: "boxupNo",
                        width: 160,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "毛重/净重(kg)",
                        dataField: "weightInfo",
                        width: 130,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "长/宽/高(mm)",
                        dataField: "sizeInfo",
                        width: 130,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "国家和地区",
                        dataField: "country",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    }
                ]
            };

            // 新增信息
            $scope.addInfo = {
                acceptId: '',
                acceptName: '',
                boxupPackDetailVOList: [],
            }

            // 获取接收人信息
            $scope.searchDispatch = function (type) {
                var param = {
                    name: "接收人",
                    defaultRoleName: '',
                    type: 'staffByWorkspace',
                    supplierOrgId: $scope.curUser.spaceId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    if (type == 'edit') {
                        $scope.editInfo.acceptName = data.name;
                        $scope.editInfo.acceptId = data.userId;                       
                    }else {
                        $scope.addInfo.acceptName = data.name;
                        $scope.addInfo.acceptId = data.userId;
                    }

                })
            }

            $scope.confirmAdd = function (isValid,status) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                if (!$scope.selectedList || $scope.selectedList.length <= 0) {
                  ybWidget.ShowMessage('请选择箱单！', MESG_TYPE.Error);
                  return;
                }
                $scope.addInfo.boxupPackDetailVOList = $scope.selectedList;
                $scope.addInfo.status = status
                var service = "device";
                let reqUrl = '/boxupPack/add';
                ybHttp.Post(service, reqUrl, $scope.addInfo).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.changeTab(0); // 新增运单后，返回列表页
                    getDataList();
                    ybWidget.ShowToaster('success', '操作成功');
                });
            };

            $scope.cancelAdd = function () {
                $scope.changeTab(0); 
            };

            // 导出模块
            $scope.exportParam = {
                allUrl: ybHttp.RequestUrl("device", "/boxupPack/exportAll"),
                exportJckUrl: ybHttp.RequestUrl("device", "/boxupPack/export"),    
                sectionParam: {
                    ids: []
                }       
                   
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                   
                        break;
                    case 2:
                     
                        break;
                    case 3:
                  
                        break;
                    case 4:
    
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.sortObj = {};

                $scope.detailInfo = {};
                $scope.deliveryObj = {};
                $scope.selectedList = [];
                $scope.markInfoEdit = {};
                $scope.toolbarConfig.showBoxupNo = false;
                $scope.addInfo = {
                    acceptId: '',
                    acceptName: '',
                    boxupPackDetailVOList: [],
                };
                $scope.markInfo = {
                    allChecked: false
                };

                $scope.curStep = 0;
                $scope.auditInfo = {};
            }

            // 获取主页面数据
            function getDataList(curPage) {
                var service = "device";
                var reqUrl = "/boxupPack/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.checkTimeShow = $filter("YbDate")(item.checkTime, 'yyyy-MM-dd HH:mm:ss');
                        item.createTimeShow = $filter("YbDate")(item.createTime, 'yyyy-MM-dd HH:mm:ss');
                        item.deliveryTimeShow = $filter("YbDate")(item.deliveryTime, 'yyyy-MM-dd HH:mm:ss');
                        item.statusShow = $scope.boxupPackStatus[item.status];
                        item.deliveryStatusShow = $filter('BoxupPackDeliveryStatus')(item.deliveryStatus);
                        item.requireDeliveryTimeShow = $filter("YbDate")(item.requireDeliveryTime, 'yyyy-MM-dd');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.orderSelectAll = function () {
                angular.forEach($scope.orderDataList, function (item) {
                    if ($scope.orderMarkInfo.allChecked && !item.isChecked) {
                        item.isChecked = true;
                        $scope.selectedList.push(item);
                    }
                    if (!$scope.orderMarkInfo.allChecked && item.isChecked) {
                        item.isChecked = false;
                        for (var i = 0; i < $scope.selectedList.length; i++) {
                            if (item.deliveryNo == $scope.selectedList[i].deliveryNo) {
                                $scope.selectedList.splice(i, 1);
                                i--;
                            }
                        }
                    }
                })
            };
            $scope.orderSelectSingle = function (item) {
                if (item.isChecked) {
                    for (var i = 0; i < $scope.selectedList.length; i++) {
                        if ($scope.selectedList[i].boxupNo === item.boxupNo) {
                            return;
                        }
                    }
                    $scope.selectedList.push(item);
                    $scope.orderMarkInfo.allChecked = true;
                    angular.forEach($scope.orderDataList, function (item) {
                        if (!item.isChecked) {
                            $scope.orderMarkInfo.allChecked = false;
                        }
                    })
                } else {
                    $scope.orderMarkInfo.allChecked = false;
                    for (var i = 0; i < $scope.selectedList.length; i++) {
                        if ($scope.selectedList[i].boxupNo == item.boxupNo) {
                            $scope.selectedList.splice(i, 1);
                            i--;
                        }
                    }
                }
            };
            $scope.delSelected = function (index) {
                angular.forEach($scope.orderDataList, function (item) {
                    if (item.boxupNo == $scope.selectedList[index].boxupNo) {
                        item.isChecked = false;
                        $scope.orderMarkInfo.allChecked = false;
                    }
                });
                $scope.selectedList.splice(index, 1);
            };

            $scope.sortObj = {};
            $scope.toSort = function (config, index) {
                if (!config[index].toSort) {
                    return;
                }
                $scope.sortObj.sortMethod = ybWidget.ToSort(config, index);
                $scope.sortObj.sortClumn = config[index].dataField;
                getBillList(1);
            };

            // 切换日期
            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false, false, false, false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };
            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };
            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };


            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.selectForAll = function () {
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                getBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                if (!type) {
                    getBillIds();
                }
            };

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }

                if (!type) {
                    getBillIds();
                }
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            // 新增表单配置
            $scope.addTableConfig = {
                scrollWidth: 800,
                fixedWidth: 40,
                tableCol: [
                    {
                        type: "",
                        name: "箱单号",
                        dataField: "boxupNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                    },
                    // {
                    //     type: "",
                    //     name: "唛头",
                    //     dataField: "marks",
                    //     width: 180,
                    //     input: true,
                    //     isShow: true,
                    //     isFixed: false,
                    // },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createTimeShow",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "发运单号",
                        dataField: "deliveryReceiptNo",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "毛重/净重(kg)",
                        dataField: "weightInfo",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "长/宽/高(mm)",
                        dataField: "sizeInfo",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "存储地点",
                        dataField: "companyAddressName",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                ]
            };

            $scope.curStep = 0;
            $scope.hasCountry = true;
            $scope.nextStep = function () {
              // 判断是否为同一个国家
              if ($scope.selectedList.length > 1) {
                for (let i = 1; i < $scope.selectedList.length; i++) {
                  if (trimALl($scope.selectedList[i].country) !== trimALl($scope.selectedList[0].country)) {
                    ybWidget.ShowMessage('只能选择同一个国家的箱单', MESG_TYPE.Error);                  
                    return;
                  }                
                }
              } 
              $scope.addInfo.country = $scope.selectedList[0].country;
              $scope.hasCountry = !!$scope.addInfo.country;
              $scope.curStep = 1;
            }

            function trimALl(str) {
              if (!str) {
                  return str;
              }
              return str.replace(/(^\s*)|(\s*$)/g, "");
            }

            $scope.prevStep = function () {
                $scope.curStep = 0;
            }

            // 新增打包单
            $scope.addData = function () {
                // getBillList(1);
                $scope.orderDataList = []
                $scope.changeTab(1);
            };

            $scope.searchBill = function (curPage) {
                getBillList(curPage);
            };

            // 左侧新增列表查询
            function getBillList(curPage) {
                var service = "device";
                var reqUrl = "/boxup/getBoxupData";
                var param = {};
                param.pageSize = $scope.orderPageInfo.pageSize;
                if (!!curPage) {
                    $scope.orderPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.orderPageInfo.curPage;
                param.filters = {
                    boxupNo: $scope.orderCondition.boxupNo,
                    purchaseContractNo: $scope.orderCondition.purchaseContractNo,
                    deliveryReceiptNo: $scope.orderCondition.deliveryReceiptNo,
                };
                $scope.orderDataList = [];
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    if (!resp.value) {
                        resp.value = { list: [] }
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createTimeShow = $filter("YbDate")(item.createTime, "yyyy-MM-dd HH:mm:ss");
                        item.deliveryStatusShow = item.deliveryStatus == 1 ? '已发运' : '未发运';
                        item.weightInfo = `${item.roughWeight || ''}/${item.weight || ''}`
                        item.sizeInfo = `${item.lenghtNum || ''}/${item.withNum || ''}/${item.hightNum || ''}`                   
                    });
                    $scope.orderPageInfo.totalRows = resp.value.total;
                    $scope.orderPageInfo.totalPages = resp.value.pages;
                    $scope.orderDataList = resp.value.list;
                });
            }

            // 详情模块
            $scope.detailTableConfig = {
                scrollWidth: 1500,
                fixedWidth: 40,
                tableCol: [
                    {
                        type: "",
                        name: "打包单号",
                        dataField: "packNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "采购合同号",
                        dataField: "purchaseContractNo",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "发运交接单号",
                        dataField: "deliveryReceiptNo",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "装箱单号",
                        dataField: "boxupNo",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "唛头",
                        dataField: "marks",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "自定义编号",
                        dataField: "boxCode",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "箱形描述",
                        dataField: "packDesc",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createTimeShow",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "长/宽/高(mm)",
                        dataField: "sizeInfo",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "毛重/净重(kg)",
                        dataField: "weightInfo",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                      type: "",
                      name: "存储地点",
                      dataField: "companyAddressName",
                      width: 180,
                      isShow: true,
                      isFixed: false
                    },
                    {
                        type: "",
                        name: "发运状态",
                        dataField: "deliveryStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                ]
            };

            function viewDetail(item) {
                getDetailInfo(item.id).then(value => {
                    if (!value) {
                        return;
                    }
                    $scope.subTabFlag = [true, false];
                    $scope.changeTab(3);
                    $scope.detailInfo = value;
                })
            }
            
            // 获取详情数据
            function getDetailInfo(id) {
                var service = "device";
                var reqUrl = "/boxupPack/getItemInfo";
                var param = {id};
                const auditStatus = ['未审核', '通过', '拒绝'];
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    resp.value.statusShow = $scope.boxupPackStatus[resp.value.status];
                    resp.value.deliveryStatusShow = resp.value.deliveryStatus == 1 ?  "已发运" : (resp.value.deliveryStatus == 4 ? "部分发运" : "未发运");

                    angular.forEach(resp.value.boxupPackDetailVOList, function (item) {
                        item.deliveryStatusShow = item.deliveryStatus == 1 ?  "已发运" : "未发运";
                        item.checkTimeShow = $filter("YbDate")(item.checkTime, 'yyyy-MM-dd HH:mm:ss');
                        item.createTimeShow = $filter("YbDate")(item.createTime, 'yyyy-MM-dd HH:mm:ss');
                        item.deliveryTimeShow = $filter("YbDate")(item.deliveryTime, 'yyyy-MM-dd HH:mm:ss');
                        item.country = resp.value.country;
                        item.weightInfo = `${item.roughWeight || ''}/${item.weight || ''}`
                        item.sizeInfo = `${item.lenghtNum || ''}/${item.withNum || ''}/${item.hightNum || ''}`
                    })
                    return resp.value;
                });
            }

            // 发运模块
            // 发运表单配置
            $scope.deliveryTableConfig = {
                scrollWidth: 800,
                fixedWidth: 40,
                tableCol: [
                    {
                        type: "",
                        name: "箱单号",
                        dataField: "boxupNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "唛头",
                        dataField: "marks",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createTime",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "发运单号",
                        dataField: "deliveryReceiptNo",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "发运状态",
                        dataField: "deliveryStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "毛重/净重(kg)",
                        dataField: "weightInfo",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "长/宽/高(mm)",
                        dataField: "sizeInfo",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "存储地点",
                        dataField: "companyAddressName",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                ]
            };

            // 发运数据
            $scope.deliveryObj = {};

            $scope.delivery = function (item) {
                getDetailInfo(item.id).then(value => {
                    if (!value) {
                        return;
                    }
                    $scope.deliveryObj = value;
                    $scope.changeTab(4);
                })
            };

            // 获取选中的数据
            function getSelectList(list, multiType = 'single', action) {
                let selectList = list.filter(item => item.isChecked);
                if (!selectList || selectList.length == 0) {
                    ybWidget.ShowMessage(`请选择要${action}的数据`, MESG_TYPE.Error);
                    return;
                }
                
                if (multiType == 'multi') {
                    return selectList;
                }
                
                if (selectList.length > 1) {
                    ybWidget.ShowMessage(`请选择1条要${action}的数据`, MESG_TYPE.Error);
                    return;
                }

                return selectList;
            }

            // 确定发运
            $scope.confirmDelivery = function () {
                let selectList = getSelectList($scope.deliveryObj.boxupPackDetailVOList, 'multi', '发运')
                if (!selectList) {
                    return;
                }

                var service = "device";
                var reqUrl = "/boxupPack/despatch";
                var param = {};
                param.id = $scope.deliveryObj.id;
                param.boxupPackDetailVOList = selectList;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.value || resp.message, MESG_TYPE.Error);
                        return;
                    }
                    getDataList();
                    $scope.changeTab(0);
                    let message = resp.message;
                    if (typeof resp.value == 'string') {
                        message = resp.value;
                    }
                    ybWidget.ShowToaster('success', message);
                });
            };

            // 装箱清单打印模块
            $scope.printBoxupNoPack = function (item) {
                var param = {
                    cusParam: {id: item.id},
                    printType: 'BoxupNoPack',
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            // 编辑模块
            $scope.editInfo = {};
            $scope.markInfoEdit = {};
            
            $scope.selectRowEdit = function (index) {
                $scope.markInfoEdit.cueRow = index;
            }

            // 编辑表单配置
            $scope.editTableConfig = {
                scrollWidth: 800,
                fixedWidth: 40,
                tableCol: [
                    {
                        type: "",
                        name: "箱单号",
                        dataField: "boxupNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "唛头",
                        dataField: "marks",
                        width: 180,
                        input: true,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createTimeShow",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "发运单号",
                        dataField: "deliveryReceiptNo",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "发运状态",
                        dataField: "deliveryStatusShow",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "毛重/净重(kg)",
                        dataField: "weightInfo",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "长/宽/高(mm)",
                        dataField: "sizeInfo",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "存储地点",
                        dataField: "companyAddressName",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                ]
            };
            $scope.editData = function (item) {
                getDetailInfo(item.id).then(value => {
                    if (!value) {
                        return;
                    }

                    $scope.editInfo = value;
                    $scope.editInfo.requireDeliveryTime =  $scope.editInfo.requireDeliveryTime ?  new Date($scope.editInfo.requireDeliveryTime) : ''
                    $scope.changeTab(2);
                })
            };

            $scope.editHasCountry = false;
            $scope.$watch('editInfo.boxupPackDetailVOList', function (n) {
              if (!n || n.length <= 0) {
                $scope.editInfo.country = '-';
                $scope.editHasCountry = true;
                return;
              }
              $scope.editInfo.country = n[0].country || '';
              $scope.editHasCountry = !!n[0].country;
            }, true);

            // 选择箱单
            $scope.selectBoxupNo = function (e) {
                if (!!$scope.toolbarConfig.showBoxupNo) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showBoxupNo = true;
                        EventBus.Publish("getBoxupData");
                    });
                }
            };

            // 删除箱单
            $scope.delBoxupNo = function (index) {
                $scope.editInfo.boxupPackDetailVOList[index].isChecked = false;
                $scope.editInfo.boxupPackDetailVOList.splice(index, 1);
            }

            // 导入唛头
            $scope.uploadMark = function (type) {
                if (!$scope[type].boxupPackDetailVOList || $scope[type].boxupPackDetailVOList.length <= 0) {
                    ybWidget.ShowMessage('请选择箱单！', MESG_TYPE.Error);
                    return;
                }
                var param = {
                    name: "唛头",
                    templateReqService: "device",
                    templateReqUrl: "/boxupPack/download",
                    importReqService: "device",
                    importReqUrl: "/boxupPack/import",
                    importErrorUrl: "",            
                };
                ybWidget.ImportFile(param).then(function (data) {
                    updateImportMark(data)
                    data.forEach(item => {
                      angular.forEach($scope[type].boxupPackDetailVOList, vo => {
                        if (item.boxupNo == vo.boxupNo) {
                          vo.marks = item.marks;
                        }
                      })
                    })
                });
            }

            function updateImportMark(list) {
              var service = "device";
              let reqUrl = '/boxupPack/updateBoxupPackDetailDO';
              let param = list.map(item => ({
                id: item.id, 
                boxupNo: item.boxupNo, 
                marks: item.marks
              }))
              ybHttp.Post(service, reqUrl, param).then(function (resp) {
                if (resp.code !== 0) {
                    ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                    return;
                }
                ybWidget.ShowToaster('success', '操作成功');
              });
            } 

            // 修改
            $scope.confirmEdit = function (isValid,status) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }

                if (!$scope.editInfo.boxupPackDetailVOList || $scope.editInfo.boxupPackDetailVOList.length <= 0) {
                  ybWidget.ShowMessage('请选择箱单！', MESG_TYPE.Error);
                  return;
                }
                var service = "device";
                let reqUrl = '/boxupPack/update';
                $scope.editInfo.status = status
                ybHttp.Post(service, reqUrl, $scope.editInfo).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.changeTab(0);
                    getDataList();
                    ybWidget.ShowToaster('success', '操作成功');
                });
            };

            // 删除模块
            $scope.delApply = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/boxupPack/delete";
                    var params = {};
                    params.id = item.id;
                    ybHttp.Post(service, reqUrl, params).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            // 审核模块
            $scope.auditInfo = {};
            $scope.auditBill = function (item) {
                getDetailInfo(item.id).then(value => {
                    if (!value) {
                        return;
                    }
                    $scope.auditInfo.id = item.id;
                    $scope.changeTab(5);
                    $scope.detailInfo = value;
                })
            };

            // 审核
            $scope.handleAudit = function (status) {
                var service = "device";
                var reqUrl = "/boxupPack/examinePack";
                var params = {};
                params.id = $scope.auditInfo.id;
                params.status = status;
                params.checkMessage = $scope.auditInfo.checkMessage;
                ybHttp.Post(service, reqUrl, params).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.changeTab(0);
                });
                
            };

            (function () {
                UserContextService.SetBtnPermission(setBtnPermission);
                $scope.setFixedWidth();
                getDataList();
            })();
        }]);
})(window, window.angular);
